package com.kgd.news.wxpay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kgd.news.utils.Constants;
import com.kgd.news.utils.wx.WxHelper;
import com.kgd.news.wxpay.constant.Constant;
import com.kgd.news.wxpay.entity.CloseOrderParams;
import com.kgd.news.wxpay.entity.CloseOrderResult;
import com.kgd.news.wxpay.util.*;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 创建时间：2016年11月9日 下午5:49:00
 *
 * @author andy
 * @version 2.2
 */

public class TransferController {

    private static final Logger LOG = Logger.getLogger(TransferController.class);

    private static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; // 企业付款

    private static final String TRANSFERS_PAY_QUERY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo"; // 企业付款查询

    /**
     * 企业向个人支付转账
     * 需要证书的
     *
     * @param openid           用户openid
     * @param partner_trade_no
     */
    public static JSONObject transferPay(String addressIp, String openid, int amount, String partner_trade_no,String nonce_str) {
        LOG.info("[/transfer/pay]");
        //业务判断 openid是否有收款资格PayUtil.getLocalIp(request)
        Map<String, String> restmap = null;
        try {
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("mch_appid", WxHelper.getAppId()); //公众账号appid
            parm.put("mchid", Constant.MCH_ID); //商户号
            parm.put("nonce_str", nonce_str); //随机字符串
            parm.put("partner_trade_no", partner_trade_no); //商户订单号
            parm.put("openid", openid); //用户openid
            parm.put("check_name", "NO_CHECK"); //校验用户姓名选项 OPTION_CHECK
            //parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
            parm.put("amount", amount + ""); //转账金额
            parm.put("desc", Constant.DESC); //企业付款描述信息
            parm.put("spbill_create_ip", addressIp); //Ip地址
            parm.put("sign", PayUtil.getSign(parm, Constant.APP_KEY));
//			StringBuffer restxml  = HttpUtil.httpsRequest(TRANSFERS_PAY, "POST", XmlUtil.xmlFormat(parm, false));
            String restxml = HttpUtils.posts(TRANSFERS_PAY, XmlUtil.xmlFormat(parm, false));
            restmap = CommonUtil.parseXml(restxml);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        JSONObject transferMap = new JSONObject();
        transferMap.put("withdraw_orderid", partner_trade_no);
        if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("return_code"))) {
            if ("SUCCESS".equals(restmap.get("result_code"))) {
                LOG.info("转账成功：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
                transferMap.put("partner_trade_no", restmap.get("partner_trade_no"));//商户转账订单号
                transferMap.put("payment_no", restmap.get("payment_no")); //微信订单号
                transferMap.put("payment_time", restmap.get("payment_time")); //微信支付成功时间
                transferMap.put("result_code", "SUCCESS"); //微信支付是否成功
                return transferMap;
            } else {
                transferMap.put("result_code", "FAIL"); //微信支付是否成功
                if (CollectionUtil.isNotEmpty(restmap)) {
                    LOG.info("转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
                    String err_code = restmap.get("err_code");
                    transferMap.put("err_code", err_code); //微信支付是否成功
                    transferMap.put("err_code_des", restmap.get("err_code_des")); //微信支付是否成功
                }
                return transferMap;
            }
        } else {
            transferMap.put("return_code", "FAIL"); //微信支付是否成功
            if (CollectionUtil.isNotEmpty(restmap)) {
                LOG.info("转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
                transferMap.put("return_msg", restmap.get("return_msg")); //微信支付是否成功
            }
            return transferMap;

        }
    }

    /**
     * 企业向个人转账查询
     *
     * @param tradeno 商户转账订单号
     */
    public static JSONObject orderPayQuery(String tradeno) {
        LOG.info("[/transfer/pay/query]");
        if (StringUtil.isEmpty(tradeno)) {
//			WebUtil.response(response, WebUtil.packJsonp(callback, JSON
//					.toJSONString(new JsonResult(-1, "转账订单号不能为空", new ResponseData()), SerializerFeatureUtil.FEATURES)));
        }
        Map<String, String> restmap = null;
        try {
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("appid", WxHelper.getAppId());
            parm.put("mch_id", Constant.MCH_ID);
            parm.put("partner_trade_no", tradeno);
            parm.put("nonce_str", PayUtil.getNonceStr());
            parm.put("sign", PayUtil.getSign(parm, Constant.APP_KEY));
            String restxml = HttpUtils.posts(TRANSFERS_PAY_QUERY, XmlUtil.xmlFormat(parm, true));
            restmap = CommonUtil.parseXml(restxml);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }
        JSONObject transferMap = new JSONObject();

        if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("return_code"))) {
            // 订单查询成功 处理业务逻辑
            if ("SUCCESS".equals(restmap.get("result_code"))) {
//                transferMap
                LOG.info("订单查询：订单" + restmap.get("partner_trade_no") + "支付成功");
                transferMap.put("partner_trade_no", restmap.get("partner_trade_no"));//商户转账订单号
                transferMap.put("openid", restmap.get("openid")); //收款微信号
                transferMap.put("payment_amount", restmap.get("payment_amount")); //转账金额
                transferMap.put("transfer_time", restmap.get("transfer_time")); //转账时间
                transferMap.put("desc", restmap.get("desc")); //转账描述
            } else {
                transferMap.put("result_code", "FAIL"); //微信支付是否成功
                if (CollectionUtil.isNotEmpty(restmap)) {
                    String err_code = restmap.get("err_code");
                    transferMap.put("err_code", err_code); //微信支付是否成功
                    transferMap.put("err_code_des", restmap.get("err_code_des")); //微信支付是否成功
                    LOG.info("订单转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
                }
            }
        } else {
            if (CollectionUtil.isNotEmpty(restmap)) {
                transferMap.put("return_msg", restmap.get("return_msg")); //微信支付是否成功
                LOG.info("订单转账失败：" + restmap.get("return_msg") + ":" + restmap.get("err_code_des"));
            }
        }
        return transferMap;
    }

    /**
     * @param orderid
     * @return
     * @throws Exception 关闭订单
     */
    public JSONObject closeOrder(String orderid) throws Exception {
        Map<String, String> restmap = null;
        Map<String, String> parameters = new HashMap<>();
        parameters.put("appid", WxHelper.getAppId());
        parameters.put("mch_id", Constant.MCH_ID);
        parameters.put("out_trade_no", orderid);//商户订单号，要唯一
        parameters.put("nonce_str", PayUtil.getNonceStr());
        String sign = PayUtil.getSign(parameters, Constant.APP_KEY);
        parameters.put("sign", sign);
        String restxml = HttpUtils.posts(Constant.URL_ORDER_ClOSE, XmlUtil.xmlFormat(parameters, false));
        System.out.println(restxml);
        restmap = CommonUtil.parseXml(restxml);
        JSONObject transferMap = new JSONObject();
        if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("return_code"))) {
            if ("SUCCESS".equals(restmap.get("result_code"))) {
                transferMap.put("result_code", restmap.get("result_code"));
                transferMap.put("result_msg", restmap.get("result_msg"));
            } else {
                transferMap.put("result_code", restmap.get("result_code"));
                transferMap.put("err_code", restmap.get("err_code"));
                transferMap.put("err_code_des", restmap.get("err_code_des"));
            }
        } else {
            transferMap.put("result_code", "FAIL");
            transferMap.put("return_msg", restmap.get("return_msg"));
        }
        return transferMap;
    }

}
